import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_view/photo_view.dart';
import 'package:dio/dio.dart';
import '../../AppConfig/Config.dart';
import 'package:image/image.dart' as img;

class ComplaintOfBeingLate extends StatefulWidget {
  const ComplaintOfBeingLate({super.key});

  @override
  State<ComplaintOfBeingLate> createState() => _ComplaintOfBeingLateState();
}

class _ComplaintOfBeingLateState extends State<ComplaintOfBeingLate> {

  List imagePaths = [];
  List base64List=[];
  String? checkImage;
  List imagePaths2 = [];
  List base64List2=[];
  String? checkImage2;
  List getFileList=[];
  List getFileList2=[];
  List loadImgList=[];
  List unLoadImgList=[];
  List returnImgList=[];
  int chkecType=-1;
  String loadTruckStr="";
  @override
  void _copyToClipboard(String copyNumber) {
    Clipboard.setData(ClipboardData(text: copyNumber));
    BrnToast.show('复制成功', context);

  }
  final ImagePicker picker = new ImagePicker();
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Text("发起投诉",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
      ),
      body: Column(
        children: [
          Expanded(child: ListView(
            children: [
              Container(
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                padding: EdgeInsets.only(top: 10.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text("运单编号：28135181324748264",style: TextStyle(color: MyColors.authTipColor,fontSize: 14.sp),),
                        GestureDetector(
                          child: Icon(Icons.filter_none,color: MyColors.authTipColor,size: 20,),
                          onTap: (){
                            _copyToClipboard("28135181324748264");
                          },
                        ),
                      ],
                    ),
                    Container(
                      width: screenSize.width-40.w,
                      margin: EdgeInsets.only(top: 8.h),
                      padding: EdgeInsets.only(top: 10.h,bottom: 10.h,right: 10.w,left: 10.w),
                      decoration: BoxDecoration(
                          color: MyColors.backgreyColor,
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Text("苏州市吴中区",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                              Icon(Icons.arrow_right_alt,color: Colors.black,size: 20,),
                              Text("苏州市吴中区",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                            ],
                          ),
                          SizedBox(height: 2.h,),
                          Text("对方姓名:小易",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                          SizedBox(height:2.h,),
                          Text("交易时间:2024-03-06 10:09:27",style: TextStyle(color: MyColors.textColor,fontSize: 13.sp),),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 8.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("投诉类型",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Container(
                      width: 140.w,
                      height: 30.h,
                      decoration: BoxDecoration(
                          border: Border.all(
                            color: MyColors.themeColor, // 边框颜色
                            width: 1.0, // 边框宽度
                            style: BorderStyle.solid, // 边框样式
                          ),
                          color: Color.fromRGBO(251, 236, 228, 1),
                          borderRadius: BorderRadius.all(Radius.circular(10))),

                      child: Center(child: Text("迟到/爽约扣款",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),),
                    ),

                  ],
                ),
              ),
              GestureDetector(
                child:  Container(
                  margin: EdgeInsets.only(top: 1.h,left: 10.w,right: 10.w),
                  padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                          Text("货物是否装上",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Container(
                        width: screenSize.width-40.w,
                        height: 30.h,
                        padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 5.h,bottom: 5.h),
                        decoration: BoxDecoration(
                            color: MyColors.backgreyColor,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            loadTruckStr==""?
                            Text("请选择货物是否装上",style: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),)
                            :Text(loadTruckStr,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                            Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 20,),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                onTap: (){
                  showModalBottomSheet(
                      context: context,
                      builder: (BuildContext context) {
                    return Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.all(Radius.circular(10))),
                      padding: EdgeInsets.only(top: 10.h,left: 10.w,right: 10.w),
                      height: 300,
                      width: screenSize.width,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              IconButton(onPressed: (){loadTruckStr=""; Navigator.pop(context);}, icon: Icon(Icons.close,color: MyColors.authTipColor,)),
                            ],
                          ),
                          TextButton(onPressed: (){
                            setState(() {
                              loadTruckStr ="货物已装上";
                            });
                            Navigator.pop(context);
                          }, child: Text("货物已装上",style: TextStyle(color:loadTruckStr =="货物已装上"?MyColors.themeColor: Colors.black,fontSize: 14.sp),)),
                          Divider(height: 1.h,color: MyColors.backgreyColor),
                          TextButton(onPressed: (){
                            setState(() {
                              loadTruckStr ="货物未装上";
                            });
                            Navigator.pop(context);
                          }, child: Text("货物未装上",style: TextStyle(color: loadTruckStr =="货物未装上"?MyColors.themeColor:Colors.black,fontSize: 14.sp),)),
                          Divider(height: 1.h,color: MyColors.backgreyColor),
                          TextButton(onPressed: (){
                            setState(() {
                              loadTruckStr ="不清楚货物是否装上";
                            });
                            Navigator.pop(context);
                          }, child: Text("不清楚货物是否装上",style: TextStyle(color:loadTruckStr =="不清楚货物是否装上"?MyColors.themeColor: Colors.black,fontSize: 14.sp),)),
                          Divider(height: 1.h,color: MyColors.backgreyColor,),
                        ],
                      )
                    );
                  },
                  );
                }
              ),


              Container(
                margin: EdgeInsets.only(top: 1.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("申请扣款金额",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 10.h,),
                    Container(
                      width: screenSize.width-40.w,
                      height: 30.h,
                      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 5.h,bottom: 5.h),
                      decoration: BoxDecoration(
                          color: MyColors.backgreyColor,
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Container(
                            width: 200.w,
                            height: 30.h,
                          padding: EdgeInsets.only(top: 6.h,),
                            child:  TextField(
                              style: TextStyle(fontSize: 14.sp),
                            decoration: InputDecoration(
                              border: InputBorder.none, // 移除边框
                              // contentPadding: EdgeInsets.zero, // 移除内部填充
                              hintText: "请输入金额",
                              hintStyle: TextStyle(color: MyColors.hintColor,fontSize: 14.sp),
                            ),
                              textAlignVertical: TextAlignVertical.center,
                          ),
                          ),
                          Text("元",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 1.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("司机迟到/爽约沟通记录凭证",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 5.h,),
                    Text("最多可以上传10个凭证",style: TextStyle(color: MyColors.hintColor),),
                    SizedBox(height: 10.h,),
                    Container(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Wrap(
                          spacing: 8.0,
                          runSpacing: 8.0,
                          children: [
                            ...imagePaths.map((path) => buildImageWidget(path,1)).toList(),
                            buildAddImageWidget(1),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 1.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("货物是否装上",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 5.h,),
                   Text("最多可以上传10个凭证",style: TextStyle(color: MyColors.hintColor),),
                    Container(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Wrap(
                          spacing: 8.0,
                          runSpacing: 8.0,
                          children: [
                            ...imagePaths2.map((path) => buildImageWidget(path,2)).toList(),
                            buildAddImageWidget(2),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 1.h,left: 10.w,right: 10.w),
                padding: EdgeInsets.only(top: 20.h,bottom: 10.h,right: 10.w,left: 10.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(10)),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("投诉内容",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height:10 ,),
                    Container(

                      child: BrnInputText(
                        autoFocus: false,
                        maxHeight: 200,
                        minHeight: 30,
                        minLines: 1,
                        maxLength: 140,
                        bgColor: MyColors.backgreyColor,
                        textInputAction: TextInputAction.newline,
                        maxHintLines: 20,
                        hint: '必填，请输入您要投诉的内容',
                        padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                        onTextChange: (text) {
                          print(text);

                          setState(() {});
                        },
                        onSubmit: (text) {
                          print(text);
                        },
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
          ),
          Container(
            height: 85.h,
            color: Colors.white,
            padding: EdgeInsets.only(top: 10.h,bottom: 40.h),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                BrnSmallOutlineButton(
                  width: screenSize.width/2-20.w,
                  radius: 30,
                  title: '发起投诉',
                  textColor: MyColors.themeColor,
                  lineColor: MyColors.themeColor,
                  fontWeight: FontWeight.w600,
                  onTap: () {
                    BrnToast.show('次按钮', context);
                  },
                ),
                SizedBox(width: 10.w,),
                BrnSmallMainButton(
                  width: screenSize.width/2-20.w,
                  radius: 30,
                  title: '联系货主',
                  textColor: Colors.white,
                  bgColor: MyColors.themeColor,
                  fontWeight: FontWeight.w600,
                  onTap: () {
                    BrnToast.show('录需求信息', context);
                  },
                )
              ],
            ),
          )
        ],
      ),
    );
  }
  Widget buildImageWidget(String imagePath,int type) {
    return Container(
      width: 85.w,
      height: 85.h,
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              // 处理点击查看图片的逻辑
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => ImageViewer(imagePath),
                ),
              );
            },
            child:
            imagePath.contains('https')==false?
            Container(
              width: 75.w,
              height: 75.h,
              decoration: BoxDecoration(
                image: DecorationImage(

                  image: FileImage(File(imagePath)),
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),
            ):Container(
              width: 75.w,
              height: 75.h,
              decoration: BoxDecoration(
                image: DecorationImage(

                  image: NetworkImage(imagePath) ,
                  fit: BoxFit.cover,
                ),
                borderRadius: BorderRadius.circular(8.0),
              ),

            ),
          ),

          Positioned(
            top: 0,
            right: 0,
            child: GestureDetector(
              child: Icon(Icons.highlight_off,size: 30,color: MyColors.authTipColor,),
              onTap: () {
                setState(() {
                  print(imagePath);
                  if(type==1) {
                    imagePaths.remove(imagePath);
                    if(getFileList.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                      getFileList.remove(imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                  }
                  if(type==2) {
                    imagePaths2.remove(imagePath);
                    if(getFileList2.toSet().contains(imagePath.replaceFirst(MyServiceUrl.imgHeader, '')))
                      getFileList2.remove(imagePath.replaceFirst(MyServiceUrl.imgHeader, ''));
                  }

                });
              },
            ),
          ),
        ],
        alignment: Alignment.center,
      ),
    );
  }

  Widget buildAddImageWidget(int checkType) {
    return GestureDetector(
        onTap: () async {
          setState(() {
            chkecType=checkType;
          });
          showModalBottomSheet(context: context, builder: (BuildContext context) {
            return Container(
              color: Colors.white,
              child:
              Stack(

                children: [

                  Column(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment:MainAxisAlignment.center,

                    children:[

                      SizedBox(height: 8.h,),
                      Row(
                        mainAxisAlignment:MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(width: 30.w,),
                          Text("上传照片",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                          IconButton(onPressed: (){
                            Navigator.of(context).pop();
                          }, icon:Icon(Icons.close,color: MyColors.authTipColor,)),
                        ],
                      ),


                      SizedBox(height: 8.h,),
                      Row(
                        children: [
                          SizedBox(width: 38.w,),
                          GestureDetector(
                            child:   Column(
                              children: [
                                Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                Text("相册",style: TextStyle(color: Colors.black),),

                              ],

                            ),
                            onTap: ()async{
                              Navigator.of(context).pop();
                              final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                              if (pickedFile != null) {

                                setState(() {
                                  checkImage = pickedFile.path;
                                  printImageMemorySize(File(checkImage!));
                                  print(checkImage);
                                  compressImage(File(checkImage!));
                                });
                              }
                            },
                          ),

                          SizedBox(width: 38.w,),
                          GestureDetector(
                            child: Column(
                              children: [
                                Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                Text("拍照",style: TextStyle(color: Colors.black),),

                              ],

                            ),
                            onTap: ()async{
                              Navigator.of(context).pop();
                              final pickedFile = await picker.pickImage(source: ImageSource.camera);

                              if (pickedFile != null) {
                                setState(() {
                                  checkImage = pickedFile.path;
                                  printImageMemorySize(File(checkImage!));
                                  print(checkImage);
                                  compressImage(File(checkImage!));

                                });
                              }
                            },
                          ),

                        ],
                      ),
                      SizedBox(height: 40.h,),
                    ],

                  ),

                ],

              ),
            );


          });


        },
        child: Image.asset("lib/Images/OrderList/图片管理上传照片.png",width: 85.w,height: 85.h,)
    );
  }

  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);

    setState(() {

      if(chkecType==1){
        imagePaths.add(checkImage.toString());
        base64List.add(base64String);

      }

      if(chkecType==2){
        imagePaths2.add(checkImage.toString());
        base64List2.add(base64String);
      }


    });
  }


}
class ImageViewer extends StatelessWidget {
  final String imagePath;

  ImageViewer(this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          // 当点击大图时，返回上一个页面
          Navigator.pop(context);
        },
        child: PhotoView(
          imageProvider: FileImage(File(imagePath)),
          minScale: PhotoViewComputedScale.contained * 0.8,
          maxScale: PhotoViewComputedScale.covered * 2,
        ),
      ),
    );
  }

}
